import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_learn/data_model.dart';
import 'package:http/http.dart' as http;

class FutureStudy extends StatefulWidget {
  const FutureStudy({super.key});

  @override
  State<FutureStudy> createState() => _FutureStudyState();
}

class _FutureStudyState extends State<FutureStudy> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Future与FutureBuilder的使用')),
      body: FutureBuilder<DataModel>(
        future: fetchPost(),
        builder: (context, snapshot) {
          switch (snapshot.connectionState) {
            case ConnectionState.none:
              return const Text('state none');
            case ConnectionState.waiting:
              return const Center(child: CircularProgressIndicator());
            case ConnectionState.active:
              return const Text('state active');
            case ConnectionState.done:
              if (snapshot.hasError) {
                return Text(
                  'error:${snapshot.error}',
                  style: const TextStyle(color: Colors.red),
                );
              }
              return Column(
                children: [
                  Text(
                    'code:${snapshot.data?.data?.code}',
                    style: const TextStyle(fontSize: 20),
                  ),
                  Text(
                    'responsePrams:${snapshot.data?.data?.requestPrams ?? ''}',
                    style: const TextStyle(fontSize: 20),
                  ),
                ],
              );
          }
        },
      ),
    );
  }

  Future<DataModel> fetchPost() async {
    var uri = Uri.parse('https://api.devio.org/uapi/test/test?requestPrams=11');
    final response = await http.get(uri);
    var result = jsonDecode(response.body);
    return DataModel.fromJson(result);
  }
}
